package com.lh.controller;

import com.lh.bean.RespBean;
import com.lh.exception.MyException;
import com.lh.service.VoteService;
import com.lh.until.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;

@CrossOrigin
@RestController
@RequestMapping
public class VoteController {
    @Autowired
    private VoteService voteService;
    //投票.

    @PostMapping("/vote")
    public RespBean vote(@RequestParam("code") String candidateJwcode, @RequestParam("token") String token) throws Exception {
        token = "token=" + URLEncoder.encode(token,"UTF-8");
        Utils utils = new Utils();
        String voterJwcode = String.valueOf(utils.getJwcode(token));
        String voterName = utils.getUsername(token);
        Integer result =voteService.insertVote(voterJwcode, candidateJwcode, voterName);
        return RespBean.ok("投票成功!今日还可以投" + result + "次");
    }
    //获取所有候选人
    @PostMapping ("/getCandidates")
    public RespBean getCandidates(@RequestBody String token) throws IOException {
        //System.out.println(token);
        ////将token的值分离出来
        //int startIndex = token.indexOf('=') + 1; // 找到等号的位置，并移动到等号后一位
        //String tokenValue = token.substring(startIndex); // 提取等号后面的部分
        token = "token=" + URLEncoder.encode(token.substring(10, token.length() - 2), "UTF-8");

        System.out.println(token);
        String voterJwcode = String.valueOf(new Utils().getJwcode(token));
        return RespBean.ok("获取成功",voteService.getCandidates(voterJwcode));
    }

    //获取某个候选人的被投票记录
    @GetMapping("/getVotesByCandidate/{candidateJwcode}")
    public RespBean getVotesByCandidate(@PathVariable("candidateJwcode") String candidateJwcode) throws MyException {
        return RespBean.ok("获取成功",voteService.getVotesByCandidate(candidateJwcode));
    }

    //重置所有投票记录
    @GetMapping("/resetVote")
    public RespBean resetVote() throws MyException {
        boolean result = voteService.resetVote();
        return RespBean.ok("重置成功",result);
    }
}
